#!/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: Huawei.py
import time
import pymongo
from selenium import webdriver

client = pymongo.MongoClient('mongodb://localhost:27017')
mydb = client["jdmpresystem"]
product = mydb['Authorproducts']

driver = webdriver.Chrome()
# 修改浏览器部分属性，绕过检测。
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    "source": """Object.defineProperty(navigator,'webdriver',{get:()=> false})"""
})
driver.get('https://www.vmall.com/list-36')
driver.implicitly_wait(10)  # 设置浏览器的等待（耗时） 智能化等待 加载完就不会等待
driver.maximize_window()
driver.find_element_by_xpath('//*[@id="category_ul"]/li[1]/a').click()


def drop_down():
    for x in range(1, 10, 2):
        j = x / 9
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        driver.execute_script(js)
        time.sleep(0.5)


drop_down()
time.sleep(3)
# for i in range(0,2):
lis = driver.find_elements_by_css_selector('#pro-list > li')
for li in lis:
    skuname = li.find_element_by_css_selector(' div > a > p.p-name').text
    isershou = skuname.find('二手机')
    if isershou == -1:
        price = li.find_element_by_class_name('p-price').find_element_by_css_selector('b').text
        price = int(price.split('¥')[1])
        comment = li.find_element_by_class_name('p-comment').find_element_by_xpath('em/span').text
        url = li.find_element_by_xpath('div/a').get_attribute('href')
        img = li.find_element_by_class_name('p-img').find_element_by_xpath('img').get_attribute('src')
        phone = {
            'brand': "华为（HUAWEI）",
            'price': price,
            'comment': comment,
            'url': url,
            'skuname': skuname,
            'img': img,
            'logourl': 'http://localhost:8002/ShopLogo/hw.png'
        }
        x = product.insert_one(phone)
        print(x)
    else:
        continue
    # driver.find_element_by_xpath('//*[@id="search-pager"]/ul/li[3]').click()
